package demo1;

import java.util.Arrays;

public class HashBuck {
    static class Node {
        //要有3个域
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int usedSize;//存放了多少个有效数据

    public static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //定义负载因子

    public HashBuck() {
        array = new Node[10];
    }

    public void put(int key, int val) {
        int index = key % array.length;

        //遍历index下标的链表是否存在key 存在更新value 不存在进行头插法插入数据
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                //更新val
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        //cur == null 链表遍历完成 没有找到这个key
        Node node = new Node(key, val);//此时进行头插
        node.next = array[index];
        array[index] = node;
        usedSize++;

        if (doLoadFactor() > DEFAULT_LOAD_FACTOR) {
            //此时需要扩容
            //array = Arrays.copyOf(array, 2 * array.length);error
            resize();
        }
    }

    private void resize() {
        Node[] newArray = new Node[2 * array.length];

        //遍历原来数组
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node nextPos = cur.next;
                int newIndex = cur.key % newArray.length;//新的下标
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;//头插

                cur = nextPos;
            }
        }
        array = newArray;
    }

    private float doLoadFactor() {
        return usedSize * 1.0f / array.length;
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];

        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }

        return -1;
    }
}
